'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/pay/pub/paySeries 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let {
			uid,
			user_id,
			nickname,
			series,
			series_id,
			pay_amount,
			tv_id,
			tv_name,
			tfid,
			invite_code,
			ad_id
		} = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------

		const user_bean = await db.collection('uni-id-users').doc(user_id).get()
		if (user_bean.data[0].balance < pay_amount) {
			console.log("云函数余额不足");
			res.code = 1;
			res.money = -1;
			res.errmsg = "余额不足";
			res.msg = "余额不足";
			return res;
		}

		//扣除用户金豆余额
		//此方法腾讯云和阿里云都支持
		let newInfo = await vk.baseDao.updateAndReturn({
			dbName: "uni-id-users",
			whereJson: {
				_id: user_id
			},
			dataJson: {
				balance: _.inc(-pay_amount)
			}
		});

		//添加金豆收支明细
		res.add_jindou = await db.collection('a_jindou_detail').add({
			user_id: user_id,
			nickname: nickname,
			change_num: pay_amount, //扣除的金豆数量
			changed_num: newInfo.balance, //支付后金豆余额
			change_reason: "购买" + tv_name + "第" + series + "集",
			type: "expend", //类型：expend:支出,income:收入。
			tfid: tfid, //投放链接的系统_ID
			invite_code: invite_code,
			ad_id: ad_id,
			_add_time: new Date().getTime()
		})

		res.add = await db.collection('a_had_pay').add({
			user_id: user_id,
			nickname: nickname,
			series: series,
			pay_amount: pay_amount,
			series_id: series_id,
			tv_name: tv_name,
			tv_id: tv_id,
			tfid: tfid, //投放链接的系统_ID
			invite_code: invite_code,
			_add_time: new Date().getTime()
		})
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
